const path = require('path')
const fs = require('fs')
const NodeSSH = require('node-ssh').NodeSSH
const moment = require('moment')

const { clearDistZip, defaultLog, successLog, errorLog } = require('../utils')

const SSH = new NodeSSH()

const connect = async (config) => {
  defaultLog('正在连接服务器')

  try {
    await SSH.connect(Object.assign({}, {
        host: config.host,
        port: config.port,
        username: config.username,
      },
      config.privateKey ? { privateKey: fs.readFileSync(path.join(process.cwd(), config.privateKey), 'utf8') } : { password: config.password }
    ))
    successLog('SSH连接成功!')

    const runCommand = async (command, cwd = config.servicePath) => {
      await SSH.exec(command, [], { cwd })
    }

    const setOldFile = async () => {
      const date = moment().format('__YYYY_MM_DD_HH_mm_ss')
      if (config.backupDist) {
        await runCommand(`mkdir -p ${config.publicPath}`)
        if (typeof config.backupDist === 'boolean') {
          await runCommand(`cp -r ${config.publicPath} ${config.publicPath}_${date}`)
        } else if (typeof config.backupDist === 'string') {
          await runCommand(`cp -r ${config.publicPath} ${config.backupDist}/${config.publicPath}_${date}`)
        }
      } 
      await runCommand(`rm -rf ${config.publicPath}`)
      await runCommand(`ls`)
    }

    const uploadZip = async () => {
      await SSH.putFiles([
        { // local 本地 ; remote 服务器 ;
          local: path.resolve(process.cwd(), `${config.publicPath}.zip`),
          remote: path.join(config.servicePath, `${config.publicPath}.zip`) 
        }
      ])
      successLog('上传成功!')
    }

    const unZip = async () => {
      await runCommand(`unzip ./${config.publicPath}.zip`) // 解压
      await runCommand(`rm -rf ./${config.publicPath}.zip`)
      successLog('解压成功!')
    }

    await setOldFile()
    await uploadZip()
    await unZip()
    SSH.dispose() // 断开连接

    await clearDistZip(config)
    
    successLog('部署完成!')
  } catch (error) {
    
    SSH.dispose() // 断开连接
    errorLog(error)
    process.exit()
  }
}

module.exports = connect
